package cn.uway.netty.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.ChannelInitializer;

public class TcpClient {
	
	    public static Bootstrap bootstrap = getBootstrap();

	    private static Logger logger = LoggerFactory.getLogger(TcpClient.class);		
	    
	    private static final Bootstrap getBootstrap(){
			EventLoopGroup group = new NioEventLoopGroup();
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class);
			bootstrap.handler(new ChannelInitializer<Channel>() {
				@Override
				protected void initChannel(Channel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					//pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
					//pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
					pipeline.addLast("handler", new TcpClientHandler());
				}
			});
			//bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
			return bootstrap;
		}
	    
	    public static final Channel getChannel(String host,int port){
			Channel channel = null;
			try {
				channel = bootstrap.connect(host, port).sync().channel();
			} 
			catch (Exception e) {
				return null;
			}
			return channel;
		}

		public static void sendMsg(String host, int port, String message) throws Exception {
			Channel channel = getChannel(host, port);
			if(channel!=null){
				byte[] data = message.getBytes("UTF-8");
				ByteBufAllocator alloc = channel.alloc();
				ByteBuf buf = alloc.buffer(data.length);
				buf.writeBytes(data);
				
				logger.debug("==============send  ByteBuf={}", buf);

				channel.writeAndFlush(buf).sync();
				channel.closeFuture().sync();
			}
		}
		
		public static void sendMsg(Channel channel,ByteBuf byteBuf) throws Exception {
			if(channel!=null){
				channel.writeAndFlush(byteBuf).sync();
				channel.closeFuture().sync();
			}
		}    
	   
}
